<template>
    <div class="item-group-container">
        <!-- 顶部操作区域 -->
        <div class="top-section">
            <transition name="search-slide">
                <div class="search-area" v-show="showSearchArea">
                    <div class="search-status" v-if="hasSearchConditions">
                        <el-tag size="small" type="info">
                            当前搜索条件: {{ getSearchConditionsText() }}
                        </el-tag>
                        <el-tag size="small" type="success" style="margin-left: 10px;">
                            找到 {{ total }} 条结果
                        </el-tag>
                    </div>
                    <el-input v-model="searchForm.ProcessCode" placeholder="请输入编码" class="search-input" clearable
                        @keyup.enter="handleSearch" />
                    <el-input v-model="searchForm.ProcessName" placeholder="请输入名称" class="search-input" clearable
                        @keyup.enter="handleSearch" />

                    <el-select v-model="searchForm.StepTypeId" placeholder="请选择群组类型" class="search-input" clearable
                        @change="handleSearch">

                        <el-option v-for="item in groupTypes" :key="item.id" :label="item.groupTypeName"
                            :value="item.id" />
                    </el-select>
                    <el-button type="primary" @click="handleSearch" class="search-btn">
                        <el-icon>
                            <Search />
                        </el-icon>
                        搜索
                    </el-button>
                    <el-button @click="clearSearch" class="clear-btn">
                        <el-icon>
                            <Close />
                        </el-icon>
                        清空
                    </el-button>
                    <el-dropdown @command="loadSearchHistory" v-if="searchHistory.length > 0">
                        <el-button class="history-btn">
                            <el-icon>
                                <Clock />
                            </el-icon>
                            历史
                            <el-icon class="el-icon--right">
                                <ArrowDown />
                            </el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="(item, index) in searchHistory" :key="index" :command="item">
                                    {{ getSearchHistoryText(item) }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </transition>
            <div class="action-buttons">
                <el-button type="primary" @click="handleAdd" class="action-btn">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新增
                </el-button>
                <el-button type="primary" @click="handleExport" class="action-btn">
                    <el-icon>
                        <Download />
                    </el-icon>
                    导出
                </el-button>
                <el-button @click="handleBatchDelete" class="action-btn delete-btn">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    删除
                </el-button>
            </div>
            <div class="utility-icons">
                <el-tooltip :content="showSearchArea ? '隐藏搜索' : '显示搜索'" placement="top">
                    <el-icon class="icon-btn" @click="toggleSearchArea" :class="{ 'active': showSearchArea }">
                        <Search />
                    </el-icon>
                </el-tooltip>
                <el-tooltip content="刷新" placement="top">
                    <el-icon class="icon-btn" @click="refreshData">
                        <Refresh />
                    </el-icon>
                </el-tooltip>
                <el-tooltip content="全屏" placement="top">
                    <el-icon class="icon-btn" @click="toggleFullscreen">
                        <Expand />
                    </el-icon>
                </el-tooltip>
                <el-tooltip content="设置" placement="top">
                    <el-icon class="icon-btn">
                        <Setting />
                    </el-icon>
                </el-tooltip>
                <el-tooltip content="关闭" placement="top">
                    <el-icon class="icon-btn">
                        <Close />
                    </el-icon>
                </el-tooltip>
            </div>
        </div>

        <!-- 数据表格 -->
        <div class="table-section">
            <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" class="data-table"
                border stripe>
                <el-table-column type="selection" width="55" />
                <el-table-column prop="index" label="序号" width="80" align="center">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="processCode" label="编码" width="150" align="center">
                    <template #header>
                        <span>编码</span>
                        <el-icon class="search-icon">
                            <Search />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column prop="processName" label="名称" width="200" align="center">
                    <template #header>
                        <span>名称</span>
                        <el-icon class="search-icon">
                            <Search />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column prop="itemTypeName" label="类型" width="150" align="center">
                    <template #header>
                        <span>类型</span>
                        <el-icon class="search-icon">
                            <Search />
                        </el-icon>
                    </template>
                    <template #default="scope">
                        <el-tag :type="getTagType(scope.row.stepTypeId)" size="small">
                            {{ scope.row.stepTypeId }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="reporting" label="报工模式" width="180" align="center">
                    <template #header>
                        <span>报工模式</span>
                        <el-icon class="search-icon">
                            <Search />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column prop="processMsg" label="描述" min-width="150" align="center" />
                <el-table-column prop="addProp" label="创建人" width="120" align="center" />
                <el-table-column prop="addTime" label="创建时间" width="160" align="center">
                    <template #header>
                        <span>创建时间</span>
                        <el-icon class="search-icon">
                            <Search />
                        </el-icon>
                        <el-icon class="sort-icon">
                            <Sort />
                        </el-icon>
                    </template>
                    <template #default="scope">
                        {{ moment(scope.row.addTime).format("YYYY-MM-DD HH:mm:ss") }}
                    </template>
                </el-table-column>
                <el-table-column prop="updTime" label="更新时间" width="160" align="center">
                    <template #default="scope">
                        {{ scope.row.updTime == null ? "" : moment(scope.row.updTime).format("YYYY-MM-DD HH:mm:ss") }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center" fixed="right">
                    <template #default="scope">
                        <el-button type="text" @click="handleEdit(scope.row)" class="action-link">
                            编辑
                        </el-button>
                        <el-button type="text" @click="handleDelete(scope.row)" class="action-link delete-link">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <div class="data-summary">
                共{{ total }}条数据
            </div>
            <div class="pagination-controls">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="编码" prop="processCode" >
                    <el-input v-model="form.processCode" placeholder="请输入群组编码" disabled/>
                </el-form-item>
                <el-form-item label="名称" prop="processName">
                    <el-input v-model="form.processName" placeholder="请输入群组名称" />
                </el-form-item>
                <el-form-item label="类型" prop="stepTypeId">
                    <el-select v-model="form.stepTypeId" placeholder="请选择群组类型" style="width: 100%">
                        <el-option label="一般" value="一般" />
                        <el-option label="维修" value="维修" />
                        <el-option label="测试" value="测试" />
                        <el-option label="锡膏" value="锡膏" />
                    </el-select>
                </el-form-item>
                <el-form-item label="报工模式" prop="reporting">
                    <el-radio-group v-model="form.reporting">
                        <el-radio value="数量" size="large">数量</el-radio>
                        <el-radio value="状态" size="large">状态</el-radio>
                    </el-radio-group>

                </el-form-item>
                <el-form-item label="描述" prop="processMsg">
                    <el-input v-model="form.processMsg" type="textarea" :rows="3" placeholder="请输入群组描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Plus,
    Download,
    Delete,
    Grid,
    Search,
    Refresh,
    Expand,
    Setting,
    Close,
    Sort,
    Clock,
    ArrowDown
} from '@element-plus/icons-vue'
import Maxios from '@/Http/MesHelp'
import { log } from 'vxe-pc-ui'
import moment from 'moment'

// 接口定义
interface ItemGroup {
    id: number
    addProp: string
    addTime: string
    updProp?: string
    updTime?: string
    isDel: boolean
    processCode: string
    processMsg: string
    processName: string
    reporting: string
    stepTypeId: string

}

interface GroupType {
    id: string
    groupTypeName: string
}

interface ProcessRoute {
    Id: number
    RouteName: string
}

// ==================== 响应式数据定义 ====================
const loading = ref(false) // 表格加载状态
const tableData = ref<ItemGroup[]>([]) // 表格数据
const selectedRows = ref<ItemGroup[]>([]) // 选中的行数据
const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示数量
const total = ref(0) // 总数据量
const dialogVisible = ref(false) // 对话框显示状态
const dialogTitle = ref('新增') // 对话框标题
const isEdit = ref(false) // 是否为编辑模式
const groupTypes = ref<GroupType[]>([{ id: '一般', groupTypeName: '一般' }, { id: '维修', groupTypeName: '维修' }, { id: '测试', groupTypeName: '测试' }, { id: '锡膏', groupTypeName: '锡膏' }]) // 群组类型数据
const processRoutes = ref<ProcessRoute[]>([]) // 工艺路线数据
const showSearchArea = ref(true) // 搜索区域显示状态
const searchHistory = ref<Array<{ ItemCode: string, ItemName: string, ItemTypeId: string }>>([]) // 搜索历史记录

// ==================== 表单数据定义 ====================
// 搜索表单数据
const searchForm = reactive({
    ProcessCode: '', // 群组编码搜索条件
    ProcessName: '', // 群组名称搜索条件
    StepTypeId: '' // 群组类型搜索条件
})

// 新增/编辑表单数据
const formRef = ref() // 表单引用
const form = ref({
    id: 0, // 物料群组ID
    processCode: '哎呀~别想了ξ( ✿＞◡❛)', // 工序编码
    processName: '', // 工序名称
    processMsg: '', // 工序描述
    stepTypeId: "", // 工序类型
    reporting: "", // 工艺路线ID.
    addTime:'', // 创建时间
    addProp: localStorage.getItem("userNickname") || '' // 创建人
})

// 表单验证规则
const rules = {
    stepTypeId: [
        { required: true, message: '请选择工序编码', trigger: 'blur' } // 群组编码必填
    ],
    processName: [
        { required: true, message: '请输入工序名称', trigger: 'blur' } // 群组名称必填
    ],
    reporting: [
        { required: true, message: '请选择报工模式', trigger: 'blur' } // 群组名称必填
    ],
    processMsg: [
        { required: true, message: '请输入对应工序描述方便后续操作', trigger: 'blur' } // 群组类型必选
    ]
}

// ==================== API接口方法 ====================
// API基础URL配置
const API_BASE_URL = '/api'  // 后端控制器路由为 api/[controller]/[action]

// 获取物料群组列表数据
const getItemGroups = async () => {
    loading.value = true
    try {
        // 调用后端API获取物料群组数据（包含分页参数）
        const response = await Maxios.get(`${API_BASE_URL}/Process/GetProcess`, {
            params: {
                ProcessCode: searchForm.ProcessCode || null,
                ProcessName: searchForm.ProcessName || null,
                StepTypeId: searchForm.StepTypeId || null,
                PageIndex: currentPage.value, // 当前页码
                PageSize: pageSize.value // 每页显示数量
            }
        })

        if (response.data.code === 200) {
            const result = response.data.data // 获取分页结果对象

            console.log('API返回数据:', result)

            // 直接使用后端返回的数据（已包含类型名称和工艺路线名称）
            tableData.value = result.list || []
            total.value = result.count || 0
            currentPage.value = result.pageIndex || 1
            pageSize.value = result.pageSize || 10

            console.log('数据设置完成:', {
                total: total.value,
                tableDataLength: tableData.value.length,
                tableData: tableData.value
            })
        } else {
            ElMessage.error(response.data.message || '获取数据失败')
        }
    }
    catch (error) {
        console.error('获取物料群组失败:', error)
        console.log('API调用详情:', {
            url: `${API_BASE_URL}/ItemGroup/ItemGroupQuery`,
            fullUrl: `http://localhost:5293${API_BASE_URL}/ItemGroup/ItemGroupQuery`,
            params: {
                ProcessCode: searchForm.ProcessCode || null,
                ProcessName: searchForm.ProcessName || null,
                ItemMsg: null,
                StepTypeId: searchForm.StepTypeId,
                PageIndex: currentPage.value,
                PageSize: pageSize.value
            }
        })
        // 如果API调用失败，使用模拟数据
        console.log('使用模拟数据...')
        const mockData: ItemGroup[] = [
            {
                id: 1,
                processCode: 'string',
                processMsg: 'string',
                processName: 'string',
                reporting: 'string',
                stepTypeId: 'string',
                addProp: '(test)管理员',
                addTime: '2024-01-15 10:30:00',
                updTime: '',
                isDel: true
            },
            {
                id: 2,
                processCode: 'string',
                processMsg: 'string',
                processName: 'string',
                reporting: 'string',
                stepTypeId: 'string',
                addProp: '(test)管理员',
                addTime: '2024-01-16 14:20:00',
                updTime: '',
                isDel: true
            },
            {
                id: 3,
                processCode: 'string',
                processMsg: 'string',
                processName: 'string',
                reporting: 'string',
                stepTypeId: 'string',
                addProp: '(test)管理员',
                addTime: '2024-01-17 09:15:00',
                updTime: '',
                isDel: true
            }
        ]

        // 过滤数据
        let filteredData = mockData
        if (searchForm.ProcessCode) {
            filteredData = filteredData.filter(item =>
                item.processCode.toLowerCase().includes(searchForm.ProcessCode.toLowerCase())
            )
        }
        if (searchForm.ProcessName) {
            filteredData = filteredData.filter(item =>
                item.processName.toLowerCase().includes(searchForm.ProcessName.toLowerCase())
            )
        }
        if (searchForm.StepTypeId) {
            filteredData = filteredData.filter(item =>
                item.stepTypeId.toLowerCase().includes(searchForm.StepTypeId.toLowerCase()))
        }

        total.value = filteredData.length
        const start = (currentPage.value - 1) * pageSize.value
        const end = start + pageSize.value
        tableData.value = filteredData.slice(start, end)
        console.log('模拟数据分页:', {
            total: total.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value,
            start,
            end,
            dataLength: tableData.value.length
        })
        console.log('模拟数据设置完成:', {
            total: total.value,
            tableDataLength: tableData.value.length,
            tableData: tableData.value
        })
    } finally {
        loading.value = false
    }
}

// ==================== 业务逻辑方法 ====================
// 根据类型ID获取对应的标签样式类型
const getTagType = (typeId: string) => {
    const typeMap: { [key:string]: string } = {
        '锡膏': 'danger',    // 原材料 - 红色标签
        '一般': 'warning',   // 成品 - 橙色标签
        '测试': 'primary',      // 上工件 - 蓝色标签
        '维修': 'success'    // 半成品 - 绿色标签
    }
    return typeMap[typeId] || 'info' // 默认返回蓝色标签
}

// 新增物料群组
const handleAdd = () => {
    isEdit.value = false // 设置为新增模式
    dialogTitle.value = '新增'
    dialogVisible.value = true // 显示对话框
    resetForm() // 重置表单数据
}

// 编辑物料群组
const handleEdit = (row: ItemGroup) => {
    isEdit.value = true // 设置为编辑模式
    dialogTitle.value = '编辑'
    dialogVisible.value = true // 显示对话框
    console.log(row);

    form.value = { ...row } // 使用展开运算符进行深拷贝
    resetForm() // 重置表单数据
}

// 删除单个物料群组
const handleDelete = async (row: ItemGroup) => {
    try {
        // 确认删除操作
        await ElMessageBox.confirm('确定要删除这个物料群组吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        console.log(row);

        // 调用删除API
        const response = await Maxios.delete(`${API_BASE_URL}/Process/ProcessDelete`, { data: { row, AddProp: row.addProp, Reporting: row.reporting, ProcessMsg: row.processMsg, StepTypeId: row.stepTypeId, ProcessCode: row.processCode, ProcessName: row.processName, Id: row.id } })

        if (response.data.code === 200) {
            ElMessage.success('删除成功')
            getItemGroups() // 刷新数据
        } else {
            ElMessage.error(response.data.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除物料群组
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的项目')
        return
    }

    try {
        // 确认批量删除操作
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个项目吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 批量删除：逐个调用删除API
        const deletePromises = selectedRows.value.map(row =>
            Maxios.post(`${API_BASE_URL}/Process/ProcessDelete`, { data: { row, AddProp: row.addProp, Reporting: row.reporting, ProcessMsg: row.processMsg, StepTypeId: row.stepTypeId, ProcessCode: row.processCode, ProcessName: row.processName, Id: row.id } })
        )

        await Promise.all(deletePromises)
        ElMessage.success('批量删除成功')
        getItemGroups() // 刷新数据
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }
}

// 导出物料群组数据（功能待开发）
const handleExport = () => {
    ElMessage.info('导出功能开发中...')
}

// 提交表单（新增或编辑物料群组）
const submitForm = async () => {
    if (!formRef.value) return

    try {
        // 表单验证
        await formRef.value.validate()

        // 准备请求数据
        const requestData = isEdit.value ? { ...form.value } : { ...form.value , AddProp: localStorage.getItem('userNickname') || '' }
        console.log(isEdit.value);

        // 根据操作类型调用不同的API
        if (isEdit.value) {
            // 编辑操作：调用更新API
            const response = await Maxios.put(`${API_BASE_URL}/Process/ProcessUpdate`, requestData)
            if (response.data.code === 200) {
                ElMessage.success(response.data.message)
            } else {
                ElMessage.error(response.data.message)
                return
            }
        } else {
            // 新增操作：调用添加API
            const response = await Maxios.post(`${API_BASE_URL}/Process/ProcessCreate`, requestData)
            if (response.data.code === 200) {
                ElMessage.success('添加成功')
            } else {
                ElMessage.error(response.data.message)
                return
            }
        }

        dialogVisible.value = false
        getItemGroups() // 刷新数据列表
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
    }
}

// 重置表单数据到初始状态
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields() // 重置表单验证状态
    }
    // 重置表单数据为默认值
    Object.assign(form, {
        Id: 0,
        processCode: '',
        processMsg: '',
        processName: '',
        reporting: '',
        stepTypeId: '',
        AddProp: ''
    })
}

// 处理表格行选择变化
const handleSelectionChange = (selection: ItemGroup[]) => {
    selectedRows.value = selection // 更新选中的行数据
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
    console.log('分页大小变化:', { oldSize: pageSize.value, newSize: size })
    pageSize.value = size // 更新每页显示数量
    currentPage.value = 1 // 重置到第一页
    getItemGroups() // 重新获取数据（后端会处理分页）
}

// 处理当前页码变化
const handleCurrentChange = (page: number) => {
    console.log('页码变化:', { oldPage: currentPage.value, newPage: page })
    currentPage.value = page // 更新当前页码
    getItemGroups() // 重新获取数据（后端会处理分页）
}

// 执行搜索操作
const handleSearch = () => {
    currentPage.value = 1 // 重置到第一页

    // 保存搜索历史记录
    if (hasSearchConditions.value) {
        const currentSearch = {
            ItemCode: searchForm.ProcessCode,
            ItemName: searchForm.ProcessName,
            ItemTypeId: searchForm.StepTypeId
        }

        // 避免重复添加相同的搜索条件
        const exists = searchHistory.value.some(item =>
            item.ItemCode === currentSearch.ItemCode &&
            item.ItemName === currentSearch.ItemName &&
            item.ItemTypeId === currentSearch.ItemTypeId
        )

        if (!exists) {
            searchHistory.value.unshift(currentSearch) // 添加到历史记录开头
            // 只保留最近10条搜索历史
            if (searchHistory.value.length > 10) {
                searchHistory.value = searchHistory.value.slice(0, 10)
            }
        }
    }

    getItemGroups() // 执行搜索并获取数据（后端会处理分页和过滤）
}

// 切换搜索区域的显示/隐藏状态
const toggleSearchArea = () => {
    showSearchArea.value = !showSearchArea.value // 切换显示状态
}

// 刷新数据列表
const refreshData = () => {
    getItemGroups() // 重新获取数据
    ElMessage.success('数据已刷新')
}

// 切换浏览器全屏模式
const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen() // 进入全屏
    } else {
        document.exitFullscreen() // 退出全屏
    }
}
// 清空搜索条件
const clearSearch = () => {
    searchForm.ProcessCode = '' // 清空编码搜索条件
    searchForm.ProcessName = '' // 清空名称搜索条件
    searchForm.StepTypeId = '' // 清空类型搜索条件
    handleSearch() // 执行搜索（此时会搜索所有数据）
    ElMessage.success('搜索条件已清空')
}

// ==================== 计算属性 ====================
// 计算属性：检查是否有搜索条件
const hasSearchConditions = computed(() => {
    return searchForm.ProcessCode || searchForm.ProcessName || searchForm.StepTypeId // 任一条件有值即为有搜索条件
})

// 获取当前搜索条件的文本描述
const getSearchConditionsText = () => {
    const conditions = []
    if (searchForm.ProcessCode) conditions.push(`编码: ${searchForm.ProcessCode}`)
    if (searchForm.ProcessName) conditions.push(`名称: ${searchForm.ProcessName}`)
    if (searchForm.StepTypeId) {
        // const groupType = groupTypes.value.find(type => type.id === searchForm.RoutingTypeId)
        conditions.push(`类型: ${searchForm.StepTypeId}`)
    }
    return conditions.join(', ') // 用逗号连接所有条件
}

// 获取搜索历史项的文本描述
const getSearchHistoryText = (item: { ItemCode: string, ItemName: string, ItemTypeId: string }) => {
    const conditions = []
    if (item.ItemCode) conditions.push(`编码: ${item.ItemCode}`)
    if (item.ItemName) conditions.push(`名称: ${item.ItemName}`)
    if (item.ItemTypeId) {
        // const groupType = groupTypes.value.find(type => type.id === item.ItemTypeId)
        conditions.push(`类型: ${item.ItemTypeId}`)
    }
    return conditions.join(', ') || '空搜索' // 如果没有条件则显示"空搜索"
}

// 加载搜索历史记录到搜索表单
const loadSearchHistory = (item: { ItemCode: string, ItemName: string, ItemTypeId: string }) => {
    searchForm.ProcessCode = item.ItemCode // 填充编码搜索条件
    searchForm.ProcessName = item.ItemName // 填充名称搜索条件
    searchForm.StepTypeId = item.ItemTypeId // 填充类型搜索条件
    handleSearch() // 执行搜索
    ElMessage.success('已加载搜索历史')
}

// 处理键盘快捷键事件
const handleKeydown = (event: KeyboardEvent) => {
    // Ctrl + F 切换搜索区域显示/隐藏
    if (event.ctrlKey && event.key === 'f') {
        event.preventDefault() // 阻止默认行为
        toggleSearchArea()
    }
    // F5 刷新数据
    if (event.key === 'F5') {
        event.preventDefault() // 阻止默认行为
        refreshData()
    }
}

// ==================== 生命周期钩子 ====================
// 组件挂载时初始化数据
onMounted(() => {
    getItemGroups() // 获取物料群组列表数据
    // 添加键盘事件监听器
    document.addEventListener('keydown', handleKeydown)
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
    document.removeEventListener('keydown', handleKeydown) // 移除键盘事件监听器
})
</script>

<style scoped>
.item-group-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.top-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
    flex: 1;
    display: flex;
    gap: 10px;
    align-items: center;
    flex-wrap: wrap;
}

.search-status {
    width: 100%;
    margin-bottom: 10px;
}

.search-input {
    width: 200px;
}

.search-btn {
    display: flex;
    align-items: center;
    gap: 5px;
}

.clear-btn {
    display: flex;
    align-items: center;
    gap: 5px;
}

.history-btn {
    display: flex;
    align-items: center;
    gap: 5px;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.action-btn {
    display: flex;
    align-items: center;
    gap: 5px;
}

.delete-btn {
    background-color: #f56c6c;
    border-color: #f56c6c;
}

.delete-btn:hover {
    background-color: #f78989;
    border-color: #f78989;
}

.utility-icons {
    display: flex;
    gap: 15px;
}

.icon-btn {
    font-size: 18px;
    color: #606266;
    cursor: pointer;
    padding: 5px;
    border-radius: 4px;
    transition: all 0.3s;
}

.icon-btn:hover {
    color: #409eff;
    background-color: #f0f9ff;
}

.icon-btn.active {
    color: #409eff;
    background-color: #f0f9ff;
}

.table-section {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-table {
    width: 100%;
}

.search-icon {
    margin-left: 5px;
    font-size: 12px;
    color: #909399;
}

.sort-icon {
    margin-left: 3px;
    font-size: 12px;
    color: #909399;
}

.action-link {
    color: #409eff;
    text-decoration: none;
    margin: 0 5px;
}

.delete-link {
    color: #f56c6c;
}

.pagination-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-summary {
    color: #606266;
    font-size: 14px;
}

.pagination-controls {
    display: flex;
    align-items: center;
}

.pagination-controls .el-pagination {
    margin: 0;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 搜索区域动画 */
.search-slide-enter-active,
.search-slide-leave-active {
    transition: all 0.3s ease;
}

.search-slide-enter-from,
.search-slide-leave-to {
    opacity: 0;
    transform: translateY(-10px);
    max-height: 0;
}

.search-slide-enter-to,
.search-slide-leave-from {
    opacity: 1;
    transform: translateY(0);
    max-height: 100px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .top-section {
        flex-direction: column;
        align-items: stretch;
    }

    .search-input {
        width: 100%;
    }

    .action-buttons {
        justify-content: center;
    }

    .utility-icons {
        justify-content: center;
    }

    .pagination-section {
        flex-direction: column;
        gap: 15px;
    }
}
</style>
